package cn.itcast.bos.service.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.repository.AreaRepository;
import cn.itcast.bos.repository.FixedAreaRepository;
import cn.itcast.bos.repository.OrderRepository;
import cn.itcast.bos.repository.WorkBillRepository;
import cn.itcast.bos.service.OrderService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderRepository orderRepository;

	@Autowired
	private FixedAreaRepository fixedAreaRepository;
	
	@Autowired
	private AreaRepository areaRepository;
	
	@Autowired
	private WorkBillRepository workBillRepository;
	
	@Autowired
	@Qualifier(value="jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	
	
	@Override
	public void saveOrder(Order order) {
//		System.out.println("调用.......**");
//		System.out.println(order.getSendCompany());
		
		order.setOrderNum(UUID.randomUUID().toString()); // 设置订单号，也可以使用登录名+时间戳形式
		order.setOrderTime(new Date());// 设置下单时间
		order.setStatus("1"); // 待取件。订单状态 1 待取件 2 运输中 3 已签收 4 异常
		Area sendArea = order.getSendArea();
		Area persistSendArea= areaRepository.findByProvinceAndCityAndDistrict(sendArea.getProvince(),sendArea.getCity(),sendArea.getDistrict());
		order.setSendArea(persistSendArea);
		Area recArea = order.getRecArea();
		Area persistRecArea= areaRepository.findByProvinceAndCityAndDistrict(recArea.getProvince(),recArea.getCity(),recArea.getDistrict());
		order.setRecArea(persistRecArea);
		
		
		/**2.2 自动分单逻辑  --基于crm完成自动分逻辑*/
		//使用webservice系统,使用客户下单的地址,查询CRM系统,返回定去ID
		Integer customer_id = order.getCustomer_id();
		String sendAddress = order.getSendAddress();
		
		String fixAreaId  = 
		WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/customer/findFixedByCustomer_idAndAddress?address="+sendAddress+"&customer_id="+customer_id)
		.type(MediaType.APPLICATION_JSON)
		.accept(MediaType.APPLICATION_JSON)
		.get(String.class);
		if (StringUtils.isNotBlank(fixAreaId)) {
			//使用定去id.查询定去
			FixedArea fixedArea = fixedAreaRepository.findOne(fixAreaId);
			//通过定区对象,获取快递员列表
			Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
			
			while(iterator.hasNext()) {
				Courier courier = iterator.next();
				if (courier!=null) {
					System.out.println("自动分单成功");
					saveOrder1(order,courier);
					saveWorkBill(order);
					return;
				}
			}
		}
		/**第二种分单逻辑*/
		for (SubArea subArea: persistSendArea.getSubareas()) {
			if (sendAddress.contains(subArea.getKeyWords())) {
				Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
				if (iterator.hasNext()) {
					Courier courier = iterator.next();
					if (courier!=null) {
						saveOrder1(order, courier);
						saveWorkBill(order);
						return;
					}
				}
			}
		}
		
		for (SubArea subArea: persistSendArea.getSubareas()) {
			if (sendAddress.contains(subArea.getAssistKeyWords())) {
				Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
				if (iterator.hasNext()) {
					Courier courier = iterator.next();
					if (courier!=null) {
						saveOrder1(order, courier);
						saveWorkBill(order);
						return;
					}
				}
			}
		}
			// 进入人工分单
			order.setOrderType("2");
			orderRepository.save(order);
	}

	


	//保存订单
	private void saveOrder1(Order order, Courier courier) {
		order.setOrderType("1");
		order.setCourier(courier);
		orderRepository.save(order);
		
	}
	
	
	//生成工单
		private void saveWorkBill(final Order order) {
			WorkBill workBill = new WorkBill();
			workBill.setType("新");
			workBill.setPickstate("新单");//取件状态
			workBill.setBuildtime(new Date());// 工单生成时间
			workBill.setRemark(order.getRemark());// 订单备注
			final String smsNumber  = RandomStringUtils.randomNumeric(4);
			workBill.setSmsNumber(smsNumber);
			workBill.setOrder(order);//工单关联订单
			workBill.setCourier(order.getCourier());//工单关联快递员
			//工单生成之后,发送短信
			jmsTemplate.send("bos_couriersms",new MessageCreator(){

				@Override
				public Message createMessage(Session session) throws JMSException {
					MapMessage mapMessage = session.createMapMessage();
					mapMessage.setString("telephone", order.getCourier().getTelephone());// 快递员电话（需发送短信）

					mapMessage.setString("num", smsNumber);// 验证码
					mapMessage.setString("sendAddress", order.getSendAddress());// 寄件地址
					//mapMessage.setString("sendName", order.getSendName()); // 寄件人
					mapMessage.setString("sendMobile", order.getSendMobile()); // 寄件人电话
					mapMessage.setString("sendMobileMsg", order.getSendMobileMsg()); // 快递员稍话
					
					return mapMessage;
				}
				
			});
			// 发送短信成功，pickstate设置为“已通知”
			workBill.setPickstate("已通知");
			workBillRepository.save(workBill);
		}



		//查询订单信息,进行回显
		@Override
		public Order findByOrderNum(String orderNum) {
			return orderRepository.findByOrderNum(orderNum);
		}

}





